package svg.sample;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;

import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.gvt.GVTTreeRendererAdapter;
import org.apache.batik.swing.gvt.GVTTreeRendererEvent;

//not useful until have all the .wav files for the letters
import javax.sound.sampled.*;

//////////////////////////////////////////////////////
/*tests one letter at a time depending on which one is chosen
 *from the combobox on the main canvas.
 *althought, it doesn't check if the letter is right or wrong
 *it just fires a neural independent of correctness :(
 */

public class SVGApplication extends JFrame {
    private JSVGCanvas canvas;

    private JComboBox cboLetters;

//  radio buttons to choose a language
    
    //Hindi Language button: learn hindi
    private JRadioButton rbtnHindi;
    //Urdu Language button:  learn urdu
    private JRadioButton rbtnUrdu;

    //Reset button: resets the canvas to draw
    private JButton btnReset;
    //Next button: takes a user to next letter
    private JButton btnNext;
    //Previous button: takes a user to previous letter
    private JButton btnPrevious;
    //Read button: gives pronunciation of the letter
    private JButton btnRead;
    //Exit button: exits the apllication
    private JButton btnExit;
    //Quiz button: allows user to quiz on either language
    private JButton btnTest;

    //array of Hindi letters 
    private String[] hindi_letters = {"a","aa","i","ii","u","uu","ksha","e","ai","o","au","am","ah", "ka","kha","ga","gha","cha","chah","ja","jha","naah","ta","tha","da","dha","nah","tah","thah","dah","dhah","na","pa","pha","ba", "bha","ma","yah","ra","la","va","sah","sha","sa","ha","ksa","tra","jna","sra"};
    //array of Urdu letters
    private String[] urdu_letters = {"aih","alit","bari","be","casmi","che","choti","dal","dal2","feq","ghain","hamza","he","he2","jim","kap","khe","lam","mim","nun","pe","pe2","qat","re","re2","saf","sin","sin2","suad","te","te2","toe","vao","zal","ze","zhe","zhe2","zoe","zuad"};

    //Current Letter Index
    private int currLetterIndex;
    //Current Langauge
    private String currLang;

    private int x1, y1, x, y;
    private boolean mouseButtonDown = false;

    private Quiz quiz;

    public SVGApplication(String title) {
        super(title);

        canvas = new JSVGCanvas();
        quiz = new Quiz(this, "Take a Quiz");

        //add mouse (e.g press, release) event handler
        canvas.addMouseListener(new MouseHandler());
        //add mouse motion (e.g mouse drag) event handler
        canvas.addMouseMotionListener(new MouseMotionHandler());

        canvas.addGVTTreeRendererListener(new RenderingHandler());
    }

    public JComponent createComponents() {
        JPanel panel = new JPanel(new BorderLayout());

        // set the current letter index to 0
        currLetterIndex = 0;

        panel.add(canvas, BorderLayout.CENTER);
        panel.add(createNorthPanel(), BorderLayout.NORTH);
        panel.add(createSouthPanel(), BorderLayout.SOUTH);
        return panel;
    }

    private JPanel createNorthPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

        JLabel lblCurrLetter = new JLabel("Current Letter");

        cboLetters = new JComboBox();
        cboLetters.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (cboLetters.getSelectedIndex() >= 0) {
                    currLetterIndex = cboLetters.getSelectedIndex();
                    move(currLang);
                }
            }
        });

        panel.add(lblCurrLetter);
        panel.add(cboLetters);

        return panel;
    }

    private JPanel createSouthPanel() {
        JPanel panel = new JPanel(new FlowLayout());

        btnReset = new JButton("Reset");
        btnReset.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });

        //PRESS NEXT BUTTON TO GET THE FILES
        btnNext = new JButton("Next>>");
        btnNext.setEnabled(false);
        btnNext.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                moveNext(currLang);
            }
        });

        btnPrevious = new JButton("<<Previous");
        btnPrevious.setEnabled(false);
        btnPrevious.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                movePrevious(currLang);
            }
        });

        //this will read the .wav file for certain letter
        btnRead = new JButton("Read");
        btnRead.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               /* String letter = getLetter(currLang, currLetterIndex);
                readLetter(currLang, letter); */
            }
        });

        btnTest = new JButton("Test");
        btnTest.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //String letter = getLetter(currLang, currLetterIndex);
                //readLetter(currLang, letter);
                showPopup();
            }
        });


        rbtnHindi = new JRadioButton("Hindi");
        rbtnHindi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                currLang = "Hindi";
                populateDropDown(hindi_letters);
                moveFirst(currLang);
            }
        });

        rbtnUrdu = new JRadioButton("Urdu");
        rbtnUrdu.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                currLang = "Urdu";
                populateDropDown(urdu_letters);
                moveFirst(currLang);
            }
        });

        ButtonGroup langGroup = new ButtonGroup();
        langGroup.add(rbtnHindi);
        langGroup.add(rbtnUrdu);

        btnExit = new JButton("Exit");
        btnExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        panel.add(rbtnHindi);
        panel.add(rbtnUrdu);

        panel.add(btnReset);
        panel.add(btnPrevious);
        panel.add(btnNext);
        panel.add(btnRead);
        panel.add(btnTest);

        panel.add(btnExit);
        return panel;
    }

    private void showPopup() {
        canvas.setSVGDocument(null);
        quiz.show();
    }

    private void populateDropDown(String[] letters) {
        cboLetters.removeAllItems();
        for (int i = 0; i < letters.length; i++) {
            cboLetters.addItem(letters[i]);
        }
    }

    private void move(String language) {
        int firstLetterIndex = 0;
        int lastLetterIndex = getLastLetterIndex(language);

        System.out.println(currLetterIndex);
        if (currLetterIndex <= lastLetterIndex) {
            String letter = getLetter(language, currLetterIndex);
            loadLetter(language, letter);
        }

        if (currLetterIndex == lastLetterIndex) {
            btnNext.setEnabled(false);
        } else {
            btnNext.setEnabled(true);
        }

        if (currLetterIndex == firstLetterIndex) {
            btnPrevious.setEnabled(false);
        } else {
            btnPrevious.setEnabled(true);
        }
    }

    private void moveFirst(String language) {
        int lastLetterIndex = getLastLetterIndex(language);
        btnPrevious.setEnabled(false);

        currLetterIndex = 0;
        if (currLetterIndex < lastLetterIndex) {
            String letter = getLetter(language, currLetterIndex);
            loadLetter(language, letter);
        }

        if (currLetterIndex == lastLetterIndex) {
            btnNext.setEnabled(false);
        } else {
            btnNext.setEnabled(true);
        }
    }

    private void moveNext(String language) {
        int lastLetterIndex = getLastLetterIndex(language);
        btnPrevious.setEnabled(true);

        // keep incrementing the index by 1 until it reaches the last letter
        if (currLetterIndex < lastLetterIndex) {
            currLetterIndex++;
            String letter = getLetter(language, currLetterIndex);
            loadLetter(language, letter);
        }

        if (currLetterIndex == lastLetterIndex) {
            btnNext.setEnabled(false);
        } else {
            btnNext.setEnabled(true);
        }
    }

    private void movePrevious(String language) {
        int firstLetterIndex = 0;
        btnNext.setEnabled(true);

        // keep decrementing the index by 1 until it reaches the first letter
        if (currLetterIndex > firstLetterIndex) {
            currLetterIndex--;
            String letter = getLetter(language, currLetterIndex);
            loadLetter(language, letter);
        }

        if (currLetterIndex == firstLetterIndex) {
            btnPrevious.setEnabled(false);
        } else {
            btnPrevious.setEnabled(true);
        }
    }

    private URL getURL(String letter) {
        
        java.io.File file = new File(letter);
        URL url = null;
        try {
          url = file.toURL();
        }
        catch (MalformedURLException ex) {
        }
        return url;
    }

    /**
     * Loads a letter on the SVG canvas
     * @param language String the currLang in use
     * @param letter String the currentLetter to load
     */
    private void loadLetter(String language, String letter) {
        //MOVE ON TO NEXT LETTER
        String svgFile = getSVGFilePath(language, letter);
        URL url = getURL(svgFile);
        canvas.loadSVGDocument(url.toString());
        //Graphics g = canvas.getGraphics();
    }

    /**
     * Generates SVG file path from the given language
     * and a letter from that language.
     * @param language String the currLang
     * @param letter String the currLetter
     * @return String location of the SVG file
     */
    private String getSVGFilePath(String language, String letter) {
        String langDir = "languages/" + language;
        String svgFile = langDir + "/" + letter + ".svg";
        return svgFile;
    }

    /**
     * Gets the index of the last letter of the specified language
     * @param language String the language whose last letter index needs be found
     * @return int the last index of chosen language
     */
    private int getLastLetterIndex(String language) {
        int lastLetterIndex = 0;

        if (language.equals("Hindi"))
            lastLetterIndex = hindi_letters.length - 1;

        if (language.equals("Urdu"))
            lastLetterIndex = urdu_letters.length - 1;

        return lastLetterIndex;
    }

    /**
     * Gets a letter from the specified language by its index
     * @param language String the language of the letter
     * @param index int index of the letter
     * @return String the letter itself
     */
    private String getLetter(String language, int index) {
        String letter = null;

        if (language.equals("Hindi"))
            letter = hindi_letters[index];

        if (language.equals("Urdu"))
            letter = urdu_letters[index];

        return letter;
    }

 
 //--------------------------------------------------not useful rite now----------------------  
    /**
     * Generates WAV file path from the given language and letter.
     * @param language String the language
     * @param letter String the letter
     * @return String location of the WAV file
     */
    private String getWAVFilePath(String language, String letter) {
        String langDir = "languages/" + language;
        String svgFile = langDir + "/" + letter + ".wav";
        return svgFile;
    }

    /**
     * Reads a WAV file associated with the given letter
     * @param language String the langauge
     * @param letter String the letter
     */
    private void readLetter(String language, String letter) {
        String wavFile = getWAVFilePath(language, letter);
        readWAV(wavFile);
    }

    /**
     * Reads a WAV file, given it's file path
     * @param file String path of the file
     */
    private void readWAV(String filePath) {
        try {
            File file = new File(filePath);

            AudioInputStream stream =
                AudioSystem.getAudioInputStream(file);
            //AudioFormat format = stream.getFormat();

            DataLine.Info info =
                new DataLine.Info(Clip.class, stream.getFormat());
            Clip clip = (Clip) AudioSystem.getLine(info);

            clip.open(stream);
            clip.start();
        } catch (IOException iox) {
            System.out.println(iox.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//-------------------------------------------------------------------------------------------

    public static void main(String[] args) {
        SVGApplication app = new SVGApplication("salrc");
        app.getContentPane().add(app.createComponents());
        //or can also add windowListener --longer code :(
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.setSize(600, 400);
        app.setVisible(true);
    }


    //MouseEventListeners: for creating points--added
    //wonder if any of these are ever needed...right now lets just leave it
    //look into later--guess they are needed...to draw on canvas :)
    class MouseHandler implements MouseListener {

        public void mouseClicked(MouseEvent e) {
            //this is how u get x and y coordinates...simple and sweet
            //System.out.println(e.getX() + ":" + e.getY());
        }

        public void mouseEntered(MouseEvent e) {}

        public void mouseExited(MouseEvent e) {}

        public void mousePressed(MouseEvent e) {
            x1 = e.getX();
            y1 = e.getY();
            mouseButtonDown = true;
        }

        public void mouseReleased(MouseEvent e) {
            mouseButtonDown = false;
        }
    }

    class MouseMotionHandler implements MouseMotionListener {
        public void mouseDragged(MouseEvent e) {
            if (mouseButtonDown) {
                Graphics2D g = (Graphics2D)canvas.getGraphics();
                x = e.getX();
                y = e.getY();
                //make the line have thickness and the color red
                Stroke stroke = new BasicStroke(2.0f);
                g.setColor(Color.red);
                g.setStroke(stroke);
                g.drawLine(x1, y1, x, y);
                x1 = x;
                y1 = y;
            }
        }

        public void mouseMoved(MouseEvent e) {}
    }

    class RenderingHandler extends GVTTreeRendererAdapter {
        public void gvtRenderingPrepare(GVTTreeRendererEvent e) {
            System.out.println("rendering");
        }

        public void gvtRenderingCompleted(GVTTreeRendererEvent e) {
            System.out.println("rendered");
            String letter = getLetter(currLang, currLetterIndex);
            if (letter != null)
                quiz.train(letter, e.getImage());
        }
    }

}
